<template>
  <div class="shift-management">
    <div class="page-header">
      <h2>班次管理</h2>
    </div>
    
    <!-- 搜索和操作区域 -->
    <div class="search-section">
      <el-form :model="searchForm" inline size="default">
        <el-form-item label="班次名称:">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入班次名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">确认检索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
      
      <div class="action-buttons">
        <el-button @click="handleDownloadTemplate" v-if="userStore.isAdmin">下载模板</el-button>
        <el-button type="primary" @click="handleImport" v-if="userStore.isAdmin">导入</el-button>
      </div>
    </div>
    
    <!-- 表格 -->
    <div class="table-section">
      <el-table
        :data="tableData"
        border
        stripe
        v-loading="loading"
        style="width: 100%"
      >
        <el-table-column prop="序号" label="序号" width="80" align="center" />
        <el-table-column prop="shiftName" label="班次名称" width="150" />
        <el-table-column prop="shiftCode" label="班次代码" width="120" align="center" />
        <el-table-column prop="startTime" label="上班时间" width="120" align="center" />
        <el-table-column prop="endTime" label="下班时间" width="120" align="center" />
        <el-table-column prop="earlyPunchInMinutes" label="提前打卡时间(分钟)" min-width="160" align="center" />
        <el-table-column prop="latePunchOutMinutes" label="延后打卡时间(分钟)" min-width="160" align="center" />
        <el-table-column prop="shiftDurationHours" label="班次时长(小时)" width="140" align="center" />
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-section">
        <span class="total-text">共{{ total }}条记录</span>
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="prev, pager, next, sizes, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    
    <!-- 导入对话框 -->
    <el-dialog
      v-model="importDialog.visible"
      title="导入班次"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-upload
        ref="uploadRef"
        :auto-upload="false"
        :on-change="handleFileChange"
        :before-remove="handleFileRemove"
        :limit="1"
        accept=".xlsx,.xls,.csv"
        drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          将文件拖到此处，或<em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            <div>只能上传xlsx/xls/csv文件</div>
            <div style="margin-top: 8px; color: #909399; font-size: 12px;">
              请确保Excel文件包含以下列：序号、班次、班次代码、开始时间、结束时间、提前打卡时间（分钟）、延后打卡时间（分钟）
            </div>
            <div style="margin-top: 4px; color: #F56C6C; font-size: 12px;">
              <strong>重要：</strong>时间格式必须为 HH:mm（如 09:30），不要包含秒！
            </div>
          </div>
        </template>
      </el-upload>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="importDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="handleImportConfirm" :loading="importDialog.loading">
            确定导入
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import { useUserStore } from '@/store/user'
import { getShiftPage, importShifts } from '@/api/shift'
import * as XLSX from 'xlsx'

const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const tableData = ref([])
const total = ref(0)

const searchForm = reactive({
  name: ''
})

const pagination = reactive({
  current: 1,
  size: 10
})

const importDialog = reactive({
  visible: false,
  loading: false
})

const uploadRef = ref()
const uploadFile = ref(null)

// 方法
const loadData = async () => {
  loading.value = true
  try {
    const params = {
      current: pagination.current,
      size: pagination.size
    }
    
    // 只有当有搜索值时才添加name参数
    if (searchForm.name && searchForm.name.trim()) {
      params.name = searchForm.name.trim()
    }
    
    console.log('查询参数:', params)
    
    const res = await getShiftPage(params)
    const data = res.data
    
    console.log('班次数据:', data)
    
    tableData.value = data.records?.map((item, index) => ({
      ...item,
      序号: (pagination.current - 1) * pagination.size + index + 1
    })) || []
    
    total.value = data.total || 0
  } catch (error) {
    console.error('加载数据失败:', error)
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  console.log('搜索班次名称:', searchForm.name)
  pagination.current = 1
  loadData()
}

const handleReset = () => {
  searchForm.name = ''
  pagination.current = 1
  loadData()
}

const handleSizeChange = (val) => {
  pagination.size = val
  pagination.current = 1
  loadData()
}

const handleCurrentChange = (val) => {
  pagination.current = val
  loadData()
}

const handleImport = () => {
  importDialog.visible = true
  uploadFile.value = null
}

const handleFileChange = (file, fileList) => {
  console.log('文件变化:', file, fileList)
  // Element Plus 的 upload 组件会传入一个包装对象，raw 属性才是原始文件
  uploadFile.value = file.raw || file
  console.log('设置的文件:', uploadFile.value)
}

const handleFileRemove = () => {
  uploadFile.value = null
}

// 将Excel时间数值转换为时间字符串
const convertExcelTimeToString = (excelTime) => {
  if (typeof excelTime === 'string') {
    // 如果已经是字符串，直接返回
    return excelTime
  }
  
  if (typeof excelTime === 'number') {
    // Excel将时间存储为一天的小数部分
    // 例如：0.5 = 12:00, 0.75 = 18:00
    const totalMinutes = Math.round(excelTime * 24 * 60)
    const hours = Math.floor(totalMinutes / 60) % 24
    const minutes = totalMinutes % 60
    
    // 格式化为 HH:mm
    return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}`
  }
  
  return excelTime
}

// 处理Excel文件并修正时间格式
const processExcelFile = async (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    
    reader.onload = (e) => {
      try {
        const data = new Uint8Array(e.target.result)
        // 重要：使用raw选项和cellDates选项来正确处理日期
        const workbook = XLSX.read(data, { 
          type: 'array',
          raw: false,  // 不使用原始值
          cellDates: true  // 将日期识别为日期对象
        })
        
        // 获取第一个工作表
        const firstSheet = workbook.Sheets[workbook.SheetNames[0]]
        // 使用raw: false确保数值被正确格式化
        const jsonData = XLSX.utils.sheet_to_json(firstSheet, { raw: false })
        
        console.log('读取到的Excel数据:', jsonData)
        
        // 处理时间格式
        const processedData = jsonData.map(row => {
          const newRow = { ...row }
          
          // 处理开始时间
          if (newRow['开始时间'] !== undefined && newRow['开始时间'] !== null) {
            newRow['开始时间'] = convertExcelTimeToString(newRow['开始时间'])
          }
          
          // 处理结束时间
          if (newRow['结束时间'] !== undefined && newRow['结束时间'] !== null) {
            newRow['结束时间'] = convertExcelTimeToString(newRow['结束时间'])
          }
          
          return newRow
        })
        
        console.log('处理后的数据:', processedData)
        
        // 重新创建Excel文件，确保时间列为文本格式
        const newWs = XLSX.utils.json_to_sheet(processedData)
        
        // 设置时间列的格式为文本
        const timeColumns = ['D', 'E'] // D列是开始时间，E列是结束时间
        const range = XLSX.utils.decode_range(newWs['!ref'])
        
        for (let col of timeColumns) {
          for (let row = range.s.r; row <= range.e.r; row++) {
            const cellAddress = col + (row + 1)
            if (newWs[cellAddress]) {
              newWs[cellAddress].t = 's' // 设置单元格类型为字符串
            }
          }
        }
        
        const newWb = XLSX.utils.book_new()
        XLSX.utils.book_append_sheet(newWb, newWs, 'Sheet1')
        
        // 生成新的文件
        const wbout = XLSX.write(newWb, { bookType: 'xlsx', type: 'array' })
        const blob = new Blob([wbout], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
        const newFile = new File([blob], file.name, { type: file.type })
        
        resolve(newFile)
      } catch (error) {
        reject(error)
      }
    }
    
    reader.onerror = () => reject(new Error('文件读取失败'))
    reader.readAsArrayBuffer(file)
  })
}

const handleImportConfirm = async () => {
  if (!uploadFile.value) {
    ElMessage.warning('请选择要导入的文件')
    return
  }
  
  console.log('准备导入文件:', uploadFile.value)
  console.log('文件名:', uploadFile.value.name)
  console.log('文件大小:', uploadFile.value.size)
  console.log('文件类型:', uploadFile.value.type)
  
  // 确保是File对象
  if (!(uploadFile.value instanceof File)) {
    ElMessage.error('文件对象无效')
    return
  }
  
  importDialog.loading = true
  try {
    // 直接发送原始文件，不做任何预处理
    const response = await importShifts(uploadFile.value)
    console.log('导入响应:', response)
    ElMessage.success('导入成功')
    importDialog.visible = false
    uploadRef.value?.clearFiles()
    uploadFile.value = null
    // 延迟一下再刷新数据，确保后端处理完成
    setTimeout(() => {
      loadData()
    }, 1000)
  } catch (error) {
    console.error('导入失败详情:', error)
    console.error('错误响应:', error.response)
    const errorMsg = error.response?.data?.message || error.message || '导入失败'
    ElMessage.error(errorMsg)
  } finally {
    importDialog.loading = false
  }
}

const handleDownloadTemplate = () => {
  // 创建示例数据
  const templateData = [
    {
      '序号': 1,
      '班次': '长白班',
      '班次代码': 'LD',
      '开始时间': '08:30',
      '结束时间': '20:30',
      '提前打卡时间（分钟）': 60,
      '延后打卡时间（分钟）': 60
    },
    {
      '序号': 2,
      '班次': '白班',
      '班次代码': 'D',
      '开始时间': '08:30',
      '结束时间': '17:00',
      '提前打卡时间（分钟）': 60,
      '延后打卡时间（分钟）': 60
    },
    {
      '序号': 3,
      '班次': '夜班',
      '班次代码': 'N',
      '开始时间': '23:00',
      '结束时间': '07:00',
      '提前打卡时间（分钟）': 60,
      '延后打卡时间（分钟）': 60
    }
  ]
  
  // 创建工作簿
  const ws = XLSX.utils.json_to_sheet(templateData)
  const wb = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(wb, ws, '班次数据')
  
  // 设置列宽
  ws['!cols'] = [
    { wch: 8 },   // 序号
    { wch: 15 },  // 班次
    { wch: 12 },  // 班次代码
    { wch: 12 },  // 开始时间
    { wch: 12 },  // 结束时间
    { wch: 20 },  // 提前打卡时间
    { wch: 20 }   // 延后打卡时间
  ]
  
  // 生成Excel文件
  XLSX.writeFile(wb, '班次导入模板.xlsx')
  
  ElMessage.info('模板下载成功！时间格式请使用 HH:mm（如 09:30），不要包含秒')
}

// 生命周期
onMounted(() => {
  loadData()
})
</script>

<style lang="scss" scoped>
.shift-management {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
  
  .page-header {
    margin-bottom: 20px;
    
    h2 {
      color: #333;
      margin: 0;
    }
  }
  
  .search-section {
    background: #f8f9fa;
    padding: 20px;
    border-radius: 4px;
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    
    .action-buttons {
      display: flex;
      gap: 10px;
    }
  }
  
  .table-section {
    flex: 1;
    display: flex;
    flex-direction: column;
    background: #fff;
    padding: 20px;
    border-radius: 4px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
    
    .el-table {
      flex: 1;
    }
    
    .pagination-section {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: 20px;
      padding-top: 20px;
      border-top: 1px solid #ebeef5;
      
      .total-text {
        color: #666;
        font-size: 14px;
      }
    }
  }
}

:deep(.el-upload-dragger) {
  height: 180px;
}

// 调整表格列宽度以充分利用空间
:deep(.el-table) {
  .el-table__header-wrapper {
    th {
      background-color: #f5f7fa;
      font-weight: 600;
      color: #303133;
    }
  }
}
</style>